<template>
  <div style="height: 100%;width: 100%">
    <div class="ecg-dialog">
      <div class="ecg-header">2. 心电图（ECG）监测</div>

      <!-- ECG 图表 -->
      <div class="ecg-chart-wrapper">
        <div ref="chartRef" class="ecg-chart"></div>
      </div>

      <!-- 指标展示 -->
      <div class="ecg-indicators">
        <div class="indicator-item" v-for="(item, index) in indicators" :key="index">
          <div class="indicator-label">{{ item.label }}</div>
          <div class="indicator-value">{{ item.value }}</div>
        </div>
      </div>
    </div>

    <div class="container" >
      <div class="inner-container">
        <div class="section-header">
          <div class="title">分析意见</div>
          <el-button class="edit-button" @click="dynamicEdit">
            <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
            <el-text v-if="!editMode"  class="edit-text">编辑</el-text>
            <el-text v-if="editMode"  class="edit-text">保存</el-text>
          </el-button>
        </div>
        <div class="section-content">
          <div v-if="editMode" class="section-content-input">
            <el-input  type="textarea" class="input-area"  :rows="4" v-model="diagnosisData"></el-input>
          </div>
          <el-text v-else class="text-content">{{ diagnosisData }}</el-text>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import * as echarts from 'echarts'
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {getEcgData} from "@/api/copd/copdReport.js";
import {getCopdReportData} from "@/api/copd/copdReport.js"

const chartRef = ref(null)
let myChart = null

const props = defineProps({
  currentReportId: Number, // 根据currentReportId的类型进行修改
  currentReport:Object
});

const ecgReportData=ref()

// 模拟生成 30 秒心电数据，采样率 125Hz，总共 3750 个点
function generateECGData(duration = 30, sampleRate = 125) {
  const totalPoints = duration * sampleRate
  const data = []

  const bpm = 72 // 心率 72次/分 => 每秒 1.2次 ≈ 每0.83秒一个心跳
  const beatInterval = sampleRate * (60 / bpm) // 每次心跳多少采样点

  for (let i = 0; i < totalPoints; i++) {
    const t = i % Math.round(beatInterval)

    // 简单心电模型：P波 + QRS + T波（仅用于视觉模拟）
    let value = 0

    // P波（轻微隆起）
    if (t >= 5 && t < 15) value = 0.05 * Math.sin((Math.PI * (t - 5)) / 10)

    // Q波（向下尖刺）
    else if (t >= 20 && t < 23) value = -0.2 * Math.exp(-Math.pow(t - 21.5, 2))

    // R波（主尖峰）
    else if (t >= 23 && t < 27) value = 1.2 * Math.exp(-Math.pow((t - 25), 2) / 1.5)

    // S波（R波后的下陷）
    else if (t >= 27 && t < 30) value = -0.3 * Math.exp(-Math.pow(t - 28.5, 2))

    // T波（缓慢隆起）
    else if (t >= 35 && t < 55) value = 0.3 * Math.sin((Math.PI * (t - 35)) / 20)

    // 添加轻微噪声
    value += (Math.random() - 0.5) * 0.05

    data.push(value)
  }

  return data
}

// const ecgData = generateECGData()

// 假设指标值（你可从 API 动态获取）
const indicators = ref([
  {label: '心率', value: '72 次/分'},
  {label: 'PR 间期', value: '160 ms'},
  {label: 'QRS 时限', value: '90 ms'},
  {label: 'QT 间期', value: '380 ms'},
])
const heartRate=ref()
onMounted(() => {
  getEcgData(props.currentReportId,props.currentReport.startTime).then((res) => {

    if(res.data.code == 200){
      ecgReportData.value=res.data.data
      console.log("ecgdata",res.data.data)
      initChart()
    }
  })


  getCopdReportData(props.currentReportId).then(res => {
    let resData = res.data.data
    console.log('111',resData)
    // frequency = resData.frequency
    // oxygen.value = resData.bloodOxygen
    // spo2.value=resData.bloodOxygen * 100
    // samplingData = resData.flowRates
    heartRate.value=resData.heartRate
    indicators.value[0].value=`${heartRate.value}次/分`

  }).catch(err => {
    console.log(err)
    console.log("请稍后重试！", 1500)
  });


})


function initChart() {
  if (!myChart) {
    myChart = echarts.init(chartRef.value)
    window.addEventListener('resize', resizeChart)
  }

  // 1) 拿到波形数组（根据你的真实字段改：waveform / data / ecg）
  const raw = Array.isArray(ecgReportData.value?.waveform)
      ? ecgReportData.value.waveform
      : (Array.isArray(ecgReportData.value) ? ecgReportData.value : [])

  // 2) 映射成 [x,y]
  const points = raw.map((val, idx) => [idx, val])

  // 3) 自适应 y 轴范围
  let yMin = 0, yMax = 0
  if (points.length) {
    yMin = points[0][1]
    yMax = points[0][1]
    for (let i = 1; i < points.length; i++) {
      const v = points[i][1]
      if (v < yMin) yMin = v
      if (v > yMax) yMax = v
    }
  }
  // 留 10% 边距，避免波形贴边被裁剪
  const pad = (yMax - yMin) * 0.5 || 0.6
  yMin -= pad
  yMax += pad

  const option = {
    tooltip: { trigger: 'axis', axisPointer: { type: 'line' } },
    xAxis: { type: 'value', show: false, max: points.length ? points[points.length - 1][0] : null },
    yAxis: {
      type: 'value',
      show: false,
      min: yMin,
      max: yMax,
      scale: true // 不强制从0开始
    },
    grid: { left: '0%', right: '0%', top: '0%', bottom: '0%' },
    dataZoom: [
      { type: 'slider', show: true, xAxisIndex: [0], start: 0, end: 10, height: 20, bottom: 5 },
      { type: 'inside', xAxisIndex: [0], start: 0, end: 10 }
    ],
    series: [
      {
        name: 'ECG',
        type: 'line',
        data: points,
        showSymbol: false,
        lineStyle: { width: 1, color: '#e74c3c' },
        // clip 默认为 true，确保在网格内绘制
      }
    ]
  }

  // 用 notMerge 强制更新坐标轴范围
  myChart.setOption(option, { notMerge: true })
}

// function initChart() {
//   myChart = echarts.init(chartRef.value)
//
//   const option = {
//     tooltip: {
//       trigger: 'axis',
//       axisPointer: {type: 'line'},
//     },
//     xAxis: {
//       type: 'value',
//       show: false,
//     },
//     yAxis: {
//       type: 'value',
//       show: false,
//       min: -1,
//       max: 1.5,
//     },
//     grid: {
//       left: '0%',
//       right: '0%',
//       top: '0%',
//       bottom: '0%',
//     },
//     dataZoom: [
//       {
//         type: 'slider',
//         show: true,
//         xAxisIndex: [0],
//         start: 0,
//         end: 10, // 默认展示前 10%
//         height: 20,
//         bottom: 5,
//       },
//       {
//         type: 'inside',
//         xAxisIndex: [0],
//         start: 0,
//         end: 10,
//       },
//     ],
//     series: [
//       {
//         name: 'ECG',
//         type: 'line',
//         data: ecgReportData.value.map((val, idx) => [idx, val]),
//         showSymbol: false,
//         lineStyle: {
//           width: 1,
//           color: '#e74c3c',
//         },
//       },
//     ],
//   }
//
//   myChart.setOption(option)
//
//   window.addEventListener('resize', resizeChart)
// }

function resizeChart() {
  if (myChart) myChart.resize()
}


const editMode=ref(false)
const diagnosisData=ref("")
const dynamicEdit = (index)=>{
  editMode.value = !editMode.value
  if (editMode.value === false){
    // updateEvaluation()
  }
}

onUnmounted(() => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped lang="scss">
.ecg-dialog {
  width: 100%;
  box-sizing: border-box;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
  //border: 1px solid rgba(0, 0, 0, 0.08);
  font-family: "Helvetica Neue", Arial, sans-serif;
  .ecg-header {
    font-size: 20px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 20px;
  }

  .ecg-chart-wrapper {
    width: 100%;
    height: 200px;
    background: #f6f9fc;
    border: 1px solid #dfe6ec;
    border-radius: 8px;
    margin-bottom: 24px;
    overflow: hidden;
  }

  .ecg-chart {
    width: 100%;
    height: 100%;
  }

  .ecg-indicators {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
  }

  .indicator-item {
    flex: 1 1 calc(25% - 12px);
    background-color: #f1f6fb;
    padding: 12px 16px;
    border-radius: 8px;
    border-left: 4px solid #3498db;
  }

  .indicator-label {
    font-size: 13px;
    color: #7f8c8d;
    margin-bottom: 4px;
  }

  .indicator-value {
    font-size: 16px;
    font-weight: bold;
    color: #2c3e50;
  }
}


.container {
  box-sizing: border-box;
  //margin: 10px;
  margin-top: 18px;

  //width: 100%;
  min-height: 180px;
  background-color: #eff2f9;
  border-radius: 10px;
  .inner-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .header {
      width: 100%;
      height: 5%;
      margin-top: 2%;
    }

    .title {
      width: 20%;
      font-size: 15px;
      font-weight: bold;
      height: 100%;
      margin-left: 20px;
      align-items: center;
      display: flex;
    }

    .section {
      width: 100%;
    }

    .section-title {
      font-size: 16px;
      margin-left: 5%;
      font-weight: bold;
    }

    .section-header {
      width: 100%;
      display: flex;
      margin-top: 20px;
      justify-content: center;
      align-items: center;
    }

    .edit-button {
      margin-left: auto;
      background-color: #eff2f9;
      border: none;
    }

    .edit-icon {
      color: #3dd986;
      margin-left: 10px;
      margin-right: 10px;
      width: 20px;
      height: 20px;
    }

    .edit-text {
      font-size: 17px;
      color: #3dd986;
    }

    .section-content {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .section-content-input{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .input-area {
      height: 100%;
      width: 95%;
    }

    .text-content {
      font-size: 16px;
      margin-left: 5%;
    }

    .footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      margin-bottom: 5vh;
    }
  }

}



</style>
